package com.example.night.service.MysqlService;

import com.example.night.data.InfluencerCoins.MonthlyInfluencerStats;
import com.example.night.data.InfluencerCoins.MonthlyInfluencerStatsRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class MonthlyInfluencerStatsMysqlService {

    @Autowired
    private final MonthlyInfluencerStatsRepository monthlyInfluencerStatsRepository;

    /**
     * 添加或更新月度统计记录
     */
    public List<MonthlyInfluencerStats> addOrUpdateMonthlyStatsBatch(List<MonthlyInfluencerStats> statsList) {
        List<MonthlyInfluencerStats> updatedStatsList = new ArrayList<>();

        for (MonthlyInfluencerStats stats : statsList) {
            // 查找已有记录
            Optional<MonthlyInfluencerStats> existingStats = monthlyInfluencerStatsRepository
                    .findByPromoteIdAndDate(stats.getPromoteId(), stats.getDate());

            if (existingStats.isPresent()) {
                // 如果已有记录，更新字段
                MonthlyInfluencerStats existing = existingStats.get();
                existing.setTotalOrders(stats.getTotalOrders());
                existing.setTotalGMV(stats.getTotalGMV());
                existing.setLeaderSysServiceMoney(stats.getLeaderSysServiceMoney());
                existing.setCoins(stats.getCoins());
                existing.setPromoteName(stats.getPromoteName());
                existing.setTotalCommission(stats.getTotalCommission());
                existing.setPhone(stats.getPhone());
                existing.setName(stats.getName()); // 保持 name 字段更新
                updatedStatsList.add(existing);
            } else {
                // 如果没有记录，则添加新记录
                updatedStatsList.add(stats);
            }
        }

        // 使用 save 方法逐一保存更新后的记录或新记录
        for (MonthlyInfluencerStats stats : updatedStatsList) {
            monthlyInfluencerStatsRepository.save(stats);
        }

        return updatedStatsList;
    }



    /**
     * 根据抖音 ID 和月份获取月度统计
     */
    public MonthlyInfluencerStats getMonthlyStats(String promoteId, Date date) {
        return monthlyInfluencerStatsRepository.findByPromoteIdAndDate(promoteId, date).orElse(null);
    }

    /**
     * 获取某个抖音 ID 的所有月度统计（按日期倒序）
     */
    public List<MonthlyInfluencerStats> getAllStatsByPromoteId(String promoteId) {
        return monthlyInfluencerStatsRepository.findAllByPromoteIdOrderByDateDesc(promoteId);
    }

    /**
     * 获取指定月份的所有达人的统计数据
     */
    public List<MonthlyInfluencerStats> getStatsByDate(Date date) {
        return monthlyInfluencerStatsRepository.findAllByDate(date);
    }

    /**
     * 删除指定抖音 ID 的所有月度统计
     */
    public boolean deleteStatsByPromoteId(String promoteId) {
        try {
            monthlyInfluencerStatsRepository.deleteByPromoteId(promoteId);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 删除指定月度统计记录
     */
    public boolean deleteMonthlyStats(String promoteId, Date date) {
        Optional<MonthlyInfluencerStats> stats = monthlyInfluencerStatsRepository.findByPromoteIdAndDate(promoteId, date);
        if (stats.isPresent()) {
            monthlyInfluencerStatsRepository.delete(stats.get());
            return true;
        }
        return false;
    }

    /**
     * 更新订单数和 GMV
     */
    public int updateOrdersAndGMV(String promoteId, int totalOrders, double totalGMV, Date date) {
        return monthlyInfluencerStatsRepository.updateOrdersAndGMV(promoteId, totalOrders, totalGMV, date);
    }

    /**
     * 更新系统服务费和金币数
     */
    public int updateServiceMoneyAndCoins(String promoteId, double leaderSysServiceMoney, int coins, Date date) {
        return monthlyInfluencerStatsRepository.updateServiceMoneyAndCoins(promoteId, leaderSysServiceMoney, coins, date);
    }
}
